﻿using AutoMapper;
using BackData;
using Details.API.Application.Command.Goods;
using Dm;
using Domain;
using Infratructure.RepositoryWay;
using MediatR;
using SqlSugar;
using SqlSugar.Extensions;
using Yitter.IdGenerator;

//using Yitter.IdGenerator;
using static Dm.net.buffer.ByteArrayBuffer;

namespace Details.API.Application.Handler.Goods
{
    /// <summary>
    /// 添加商品
    /// </summary>
    public class AddGoodsHandler:IRequestHandler<AddGoodsCommand,APIResult<int>>
    {
        private readonly IRepository<GoodsModel> goodway;
        private readonly ILogger<AddGoodsHandler> log;
        private readonly IMapper mapper;


        public AddGoodsHandler(IRepository<GoodsModel> goodway, ILogger<AddGoodsHandler> log, IMapper mapper)
        {
            this.goodway = goodway;
            this.log = log;
            this.mapper = mapper;
        }
           

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="request">商品信息</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<int>> Handle(AddGoodsCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res=new APIResult<int>();
            
            var  goods=mapper.Map<GoodsModel>(request);
          // goods.Id=client.Insertable(goods).ExecuteReturnSnowflakeId();
           goods.Id=YitIdHelper.NextId();  //雪花id
            var result=await goodway.AddAsync(goods);
           
            if(result>0)
            {
                res.Message = $"商品{request.Goodsname}添加成功";
                log.LogInformation($"商品{request.Goodsname}添加成功");
                res.Code = StateCode.OK;
                res.Data = result;
            }
            else
            {
                res.Message = $"商品{request.Goodsname}添加失败";
                log.LogError($"商品{request.Goodsname}添加失败");
                res.Code = StateCode.OK;
            }
            return res;
  
        }
    }
}
